package com.sunwayworld.basemodule.coredata.pjproductpackage.service.impl;

import com.sunwayworld.basemodule.coredata.product.bean.LimsProductMainPuposeBean;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.spring.annotation.GikamBean;

import com.sunwayworld.basemodule.coredata.pjproductpackage.dao.LimsTestPackageProductDao;
import com.sunwayworld.basemodule.coredata.pjproductpackage.bean.LimsTestPackageProductBean;
import com.sunwayworld.basemodule.coredata.pjproductpackage.service.LimsTestPackageProductService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;

import java.util.List;
import java.util.stream.Collectors;

@Repository
@GikamBean
public class LimsTestPackageProductServiceImpl implements LimsTestPackageProductService {

    @Autowired
    private LimsTestPackageProductDao limsTestPackageProductDao;

    @Override
    @SuppressWarnings("unchecked")
    public LimsTestPackageProductDao getDao() {
        return limsTestPackageProductDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        List<LimsTestPackageProductBean> fromData = jsonWrapper.parse(LimsTestPackageProductBean.class);
        if (fromData.isEmpty()) {
            return 0L;
        }
        List<LimsTestPackageProductBean> exists = this.selectListByFilter(SearchFilter.instance().match("packageid", fromData.get(0).getPackageid()).filter(MatchPattern.EQ));
        List<Long> deleteIds = exists.stream().filter(e -> fromData.stream().noneMatch(f -> f.getProductmainid().equals(e.getProductmainid()))).map(LimsTestPackageProductBean::getId).collect(Collectors.toList());
        List<LimsTestPackageProductBean> inserts = fromData.stream().filter(f -> exists.stream().noneMatch(e -> e.getProductmainid().equals(f.getProductmainid()))).collect(Collectors.toList());
        if (!deleteIds.isEmpty()) {
            getDao().deleteByIdList(deleteIds);
        }
        if (!inserts.isEmpty()) {
            inserts.forEach(i -> {
                i.setId(ApplicationContextHelper.getNextIdentity());
            });
            getDao().fastInsert(inserts);
        }
        return 1L;
    }

}
